package util

import (
	"encoding/json"
	"fmt"
	"github.com/hashicorp/consul/api"
	"log"
	"strconv"
)

func StoreKeyValue(consul_addr string, key string, value string) {

	if consul_addr == "" || key == "" || value == "" {
		return
	}

	consulConf := api.DefaultConfig()
	consulConf.Address = consul_addr
	client, err := api.NewClient(consulConf)

	bys, _ := json.Marshal(&value)

	kv := &api.KVPair{
		Key:   key,
		Flags: 0,
		Value: bys,
	}
	client.KV().Put(kv, nil)
	if err != nil {
		log.Printf("error: %v", err)
	}
	fmt.Println(" store data key:", kv.Key, " value:", string(bys))
}

func GetKeyValue(consul_addr string, key string) string {
	consulConf := api.DefaultConfig()
	consulConf.Address = consul_addr
	client, err := api.NewClient(consulConf)
	kv, _, err := client.KV().Get(key, nil)
	if kv == nil {
		return ""
	}
	if err != nil {
		log.Printf("error: %v", err)
	}

	return string(kv.Value)
}

/**
发现服务
*/
func DiscoverService(address string, serviceName string, tag string) map[string][]string {

	addrs := make(map[string][]string, 0)

	var lastIndex uint64
	config := api.DefaultConfig()
	config.Address = address

	client, err := api.NewClient(config)
	if err != nil {
		fmt.Println("api new client is failed, err:", err)
		return addrs
	}

	services, metainfo, err := client.Health().Service(serviceName, tag, false, &api.QueryOptions{
		WaitIndex: lastIndex,
	})
	if err != nil {
		fmt.Println("error retrieving instances from Consul: ", err)
	}
	lastIndex = metainfo.LastIndex

	array := make([]string, 0)
	for _, service := range services {
		array = append(array, service.Service.Address+":"+strconv.Itoa(service.Service.Port))
	}
	addrs[serviceName] = array
	fmt.Println(StructToJson(addrs))

	return addrs
}

/**
注册服务
*/
func ServiceRegistger(consulAddr string, serviceName string, ip string, port int, Timeout string, internal string) {
	config := api.DefaultConfig()
	config.Address = consulAddr
	client, err := api.NewClient(config)
	if err != nil {
		log.Fatal("consul client error : ", err)
	}
	//创建一个新服务。
	registration := new(api.AgentServiceRegistration)
	registration.ID = UniqueId()
	registration.Name = serviceName
	registration.Port = port
	registration.Tags = []string{serviceName}
	registration.Address = ip

	//增加check。
	check := new(api.AgentServiceCheck)
	check.HTTP = fmt.Sprintf("http://%s:%d%s", registration.Address, registration.Port, "/check")
	//设置超时 5s。
	check.Timeout = Timeout
	//设置间隔 5s。
	check.Interval = internal
	//注册check服务。
	registration.Check = check
	log.Println("get check.HTTP:", check)

	err = client.Agent().ServiceRegister(registration)

	if err != nil {
		log.Fatal("register server error : ", err)
	}

}
